package com.example.common.recycler.base;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * 每种数据类型对应的BindView基类
 * 用户只需继承此类并实现抽象方法即可
 *
 * @param <T> 与视图对应的实体类
 */
public abstract class BaseBindView<T, VH extends RecyclerView.ViewHolder> {
    public Type itemBeanType; //存放泛型T的实际类型

    public BaseBindView() {
        itemBeanType = getItemBeanType(getClass());
    }

    /**
     * 数据与视图绑定
     * 用户可以在这里将数据设置给具体的视图对象
     *
     * @param holder
     * @param position
     * @param item
     * @param payloads 要size为0,表示全局刷新，如果不为0,则表示局部刷新
     */
    public void bindViewData(VH holder, int position, T item, @NonNull List<Object> payloads) {
        if (payloads.isEmpty()) {
            bindViewDataWithFull(holder, position, item);
        } else {
            bindViewDataWithPartial(holder, position, item, payloads);
        }
    }

    /**
     * 回收时
     *
     * @param holder
     */
    public void onViewRecycled(@NonNull VH holder) {
    }

    /**
     * 全局刷新
     *
     * @param holder
     * @param position
     * @param item
     */
    public abstract void bindViewDataWithFull(VH holder, int position, T item);

    /**
     * 局部刷新
     *
     * @param holder
     * @param position
     * @param item
     */
    public void bindViewDataWithPartial(VH holder, int position, T item, @NonNull List<Object> payloads) {
    }

    /**
     * 获得泛型T的实际类型
     *
     * @param subclass 子类
     * @return
     */
    public Type getItemBeanType(Class<?> subclass) {
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return parameterized.getActualTypeArguments()[0];
    }
}